package calculator;

import java.util.Stack;

/**
 * @program: javase
 * @description:
 * @author: luolidong
 * @create: 2021-07-07 15:17
 * @version: 1.0
 */
public class Demo {
    public int calculate(String s){
        int len=s.length();
        char preOperator='+';
        int num=0;
        Stack<Integer> stack=new Stack<>();
        for (int i = 0; i <len ; i++) {
            char c=s.charAt(i);
            /**多位数字如：123，需要字符拼接 */
            if(Character.isDigit(c)){//数字
                num=num*10+c-'0';
            }
            //当是最后一个操作数，直接计算
            if(!Character.isDigit(c)&&c!=' '||i==len-1){
                switch (preOperator){//这里是前一个操作符
                    case '+':{
                        stack.push(num);
                        break;
                    }
                    case '-':{
                        stack.push(-num);
                        break;
                    }
                    case '*':{
                        stack.push(num*stack.pop());
                        break;
                    }
                    case '/':{
                        stack.push(stack.pop()/num);
                        break;
                    }
                }
                preOperator=c;//当前操作符赋值
                num=0;
            }
        }
        //全部相加
        int ans=0;
        while (!stack.isEmpty()){
            ans+=stack.pop();
        }
        return ans;
    }

    public static void main(String[] args) {
        int calculate = new Demo().calculate("111/51+211*13-41*41");
        System.out.println(111/51+211*13-41*41);
        System.out.println(calculate);
    }
}
